/* Configuration */		
	//http://212.26.144.107:1456/kadastrova-karta
	var serverMap = 'http://212.26.144.107:8092';
	//var serverMap = 'http://10.0.6.53';


	var untiled;
	var tiled;
	var pureCoverage = false;

	
	// pink tile avoidance
	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
	// make OL compute scale according to WMS spec
	OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
	
	//OpenLayers.ProxyHost = "http://212.26.144.107:4156/cgi-bin/proxy.cgi?url=";	
	OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
	  
	var map, infoo;
	var mapBounds = new OpenLayers.Bounds(21.921242623, 43.5341787107, 42.0119321532, 53.3790101853);
	var mapMinZoom = 2;
	var mapMaxZoom = 22

    // avoid pink tiles
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.Util.onImageLoadErrorColor = "transparent";
    
    
    $(document).ready(function(){    
    	var map = document.getElementById("map");
	    var leftSideWidth = 0; 
	    
	    map.style.height = (getWindowHeight()-72) + "px";	    	
	    map.style.width = (getWindowWidth()-2-280) + "px";
		//if (map.updateSize) { map.updateSize(); };
    	
    	init();    
    	//resize();  
    });

    function init(){
		   var options = {
	                controls: [],
	                projection: new OpenLayers.Projection("EPSG:900913"),
	                displayProjection: new OpenLayers.Projection("EPSG:4326"),
	                units: "m",
	                numZoomLevels: 22,
	                maxResolution: 156543.0339,
	                maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
		        };
	        
		   	map = new OpenLayers.Map('map', options); 
            
		    // if this is just a coverage or a group of them, disable a few items,
		    // and default to jpeg format
		    format = 'image/png8';
		    if(pureCoverage) {
		        format = "image/jpeg";
		    }


		   kadpodil = new OpenLayers.Layer.WMS(
                    "Кадастровий поділ", serverMap+"/vector/geoserver/gwc/service/wms?tiled=true",
                    {
                        LAYERS: 'kadastr',
                        STYLES: '',
                        format: 'image/png8',
                        tiled: true,
                        transparent: 'true',
                        //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                    },
                    {
                        buffer: 0,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: false,
                        yx : {'EPSG:900913' : false}
                    } 
                );


                mosaic = new OpenLayers.Layer.WMS(
                    "dzk:mosaic - Tiled", serverMap+"/rastr/geoserver/gwc/service/wms?tiled=true",
                    {
                        LAYERS: 'dzk:mosaic',
                        STYLES: '',
                        format: 'image/jpeg',
                        tiled: true,
                        //tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                    },
                    {
                        buffer: 0,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: true,
                        yx : {'EPSG:900913' : true}
                    } 
                );

/*    
var layer_wfs = new OpenLayers.Layer.Vector('Слой WFS', {
            strategies: [new OpenLayers.Strategy.Fixed({preload: true})],
            protocol: new OpenLayers.Protocol.WFS({
                version: '1.1.0',
                url: 'http://212.26.144.107:8092/vector/geoserver/wfs',
                featureType: 'obl',
                featureNS: 'http://localhost/test',
                srsName: 'EPSG:900913'
            }),
            visibility: true
    }); 
*/

		var gsat = new OpenLayers.Layer.Google(
    			"Google - космос",
    			{type: google.maps.MapTypeId.SATELLITE, isBaseLayer: true, numZoomLevels: 22}
    			// used to be {type: G_SATELLITE_MAP, numZoomLevels: 22}
		); 


		var gphy = new OpenLayers.Layer.Google(
    			"Google - фізична карта",
    			{type: google.maps.MapTypeId.TERRAIN}
    			// used to be {type: G_PHYSICAL_MAP}
		);

		var gmap = new OpenLayers.Layer.Google(
    			"Google - карта", // the default
    			{numZoomLevels: 22, isBaseLayer: true}
    			// default type, no change needed here
		);

		var ghyb = new OpenLayers.Layer.Google(
    			"Google - космос гібрід",
    			{type: google.maps.MapTypeId.HYBRID, numZoomLevels: 22}
    			// used to be {type: G_HYBRID_MAP, numZoomLevels: 20}
		);


	     tmsoverlay = new OpenLayers.Layer.TMS( "Карта масштабу М 1:100000", "",
	            {   // url: '', serviceVersion: '.', layername: '.',
					type: 'jpg', getURL: overlay_getTileURL, alpha: true, 
					isBaseLayer: true
	            });
			if (OpenLayers.Util.alphaHack() == false) { tmsoverlay.setOpacity(0.7); }
			
        tmsoverlay_orto = new OpenLayers.Layer.TMS( "Ортофотоплани", "",
        {   // url: '', serviceVersion: '.', layername: '.',
                                type: 'jpg', getURL: overlay_getTileURL, alpha: true,
                                isBaseLayer: true
        });
        if (OpenLayers.Util.alphaHack() == false) { tmsoverlay_orto.setOpacity(0.7); }		
        
        /*tmsoverlay_orto2 = new OpenLayers.Layer.TMS( "Ортофотоплани ДЗА", "",
                {   // url: '', serviceVersion: '.', layername: '.',
                                        type: 'jpg', getURL: overlay_getTileURL, alpha: true,
                                        isBaseLayer: true
                });
        if (OpenLayers.Util.alphaHack() == false) { tmsoverlay_orto2.setOpacity(0.7); }		*/        

/*
            
                temp_parcel = new OpenLayers.Layer.WMS(
                    "участки_временные", serverMap+"/geoserver/dzk/wms",
                    {
                        LAYERS: 'dzk:tempdil',
                        STYLES: '',
			transparent: 'true',
                        format: format
                    },
                    {
                       singleTile: true, 
                       ratio: 1, 
                       isBaseLayer: false,
                       yx : {'EPSG:900913' : false}
                    } 
                );
*/

         //map.addLayers([parcel, kadpodil, gmap, gsat, tmsoverlay,]);
			
		select = new OpenLayers.Layer.Vector("Selection", {styleMap:
				new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"])
		});
		hover = new OpenLayers.Layer.Vector("Hover"); 
				
		map.addLayers([gmap, gsat, gphy, ghyb, tmsoverlay, tmsoverlay_orto, kadpodil]);		

        map.addControl(new OpenLayers.Control.Zoom());
		map.addControl(new OpenLayers.Control.DragPan({
			enableKinetic: false
		}));
        map.addControl(new OpenLayers.Control.Navigation());
        map.addControl(new OpenLayers.Control.Scale(OpenLayers.Util.getElement('scale')));        
        //map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
		map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('map_show_layers')}));      
		//map.addControl(new OpenLayers.Control.ZoomBox({'div':OpenLayers.Util.getElement('map_zoom_box')}));
		
		//alert( mapBounds.transform(map.displayProjection, map.projection ));

        map.zoomToExtent( mapBounds.transform(map.displayProjection, map.projection ) );
        
    	var popup = false;
                
        infoo = new OpenLayers.Control.WMSGetFeatureInfo({
        //layerUrls: serverMap+'/vector/geoserver/wms',
        layerUrls: serverMap+'/vector/geoserver/wms',
        
	    //layers: 'dilanka',
	    //infoFormat: 'application/vnd.ogc.gml',
	    //infoFormat: 'text/html',
        infoFormat: 'text/plain',
	    title: 'Identify features by clicking',
            queryVisible: true,
            eventListeners: {
                getfeatureinfo: function(event) { 		
	        		
	        		
	        		//alert(event.text);
	        		
	        		var info = explode('\n', event.text);
	        		
	        		var oInfo = {
	        			koatuu : [],
	        			zone : [],
	        			quarter : [],
	        			parcel : [],
	        			natoobl : '',
	        			patoobl : '',
	        			natoray : '', 
	        			vpor : [],
	        			vposs : []
	        		};	
	        		
	        		$.each(info, function(index, row){
	        			var items = explode('=', row);	     
	        			if(items.length == 2)
	        			switch(trim(new String(items[0]))){
        					case 'koatuu':	oInfo.koatuu.push(lpad(trim(new String(items[1])), 10, '0'));break;
        					case 'zona':	oInfo.zone.push(lpad(trim(new String(items[1])), 2, '0'));break;
        					case 'kvartal':
        					case 'kvart':	oInfo.quarter.push(lpad(trim(new String(items[1])), 3, '0'));break;
        					case 'parcel':	oInfo.parcel.push(lpad(trim(new String(items[1])), 4, '0'));break;
        					case 'natoobl':	oInfo.natoobl = items[1]; break;
        					case 'natoray':	oInfo.natoray = items[1]; break;
        					case 'patoobl':	oInfo.patoobl = items[1]; break;
        					case 'vpor':	oInfo.vpor.push(items[1]); break;
        					case 'vposs': oInfo.vposs.push(items[1]); break;
        				}	        		
	        		}); 	        		
	        		
	        		//alert(dump(oInfo));
	        		var output = 'Інформацію не знайдено';
	        		if(oInfo.parcel.length > 0){        					
	        					
			        			output = '<h3>Ділянки(а)</h3>';
			        			output += '<ul>';	 
			        			$.each(oInfo.parcel, function(k, v){
			        				output += '<li>';				        					
				        				output += '<span>'+oInfo.koatuu[k]+':'+oInfo.zone[k]+':'+oInfo.quarter[k]+':'+oInfo.parcel[k]+'</span>';	
				        				var p = getParcelInfo(oInfo.koatuu[k], oInfo.zone[k], oInfo.quarter[k], oInfo.parcel[k]);
				        				if(p.length > 0){
				        					if(p[0]['ownershipvalue']) output += '<div>'+p[0]['ownershipvalue']+'</div>';
				        					if(p[0]['purpose']) output += '<div>'+p[0]['purpose']+'</div>';					        				
					        				//if(p[0]['ownershipcode']) output += '<div>'+p[0]['ownershipcode']+'</div>';					        				
					        				if(p[0]['area']) output += '<div>'+p[0]['area']+' '+p[0]['unit_area']+'</div>';
				        				}
			        				output += '</li>';	
			        			});	        		       			
			        			output += '</ul>';	 	 
							
        			}if(oInfo.parcel.length == 0 && oInfo.quarter.length > 0) // Квартал
	        		{
        				$.ajax({
							url : '/kadastrova-karta/get-Region-Info',
							dataType: 'json',
							async: false,
							data : {'koatuu' : oInfo.koatuu[0]},
 						    success :function(data){     
							
	        					output = '<h3>'+data['data']['region']+' область</h3>';
	    	        			output += '<ul>';	  
	    	        			output += '<li>';
    	        				output += '<div class="label">Район</div>';
    	        				output += '<div class="data">'+data['data']['district']+'</div>';
    	        			output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Коатуу</div>';
	    	        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
	    	        			output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Зона</div>';
	    	        				output += '<div class="data">'+oInfo.zone[0]+'</div>';
	            				output += '</li>';
	    	        			output += '<li>';
	    	        				output += '<div class="label">Квартал</div>';
	    	        				output += '<div class="data">'+oInfo.quarter[0]+'</div>';
	    	        			output += '</li>';	        			
	    	        			output += '</ul>';	     	        			
							}
        				});        				 
	        			
	        		}else	if(oInfo.natoray != ''){ // Район	        		
	        			output = '<h3>'+oInfo.natoobl+' область</h3>';
		        			output += '<ul>';
		        			output += '<li>';
	        					output += '<div class="label">Район</div>';
	        					output += '<div class="data">'+oInfo.natoray+'</div>';
	        				output += '</li>';
		        			output += '<li>';
		        				output += '<div class="label">Коатуу</div>';
		        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
		        			output += '</li>';
	        			output += '</ul>';	 	        			
	        		}else if(oInfo.patoobl != ''){	// Область        		
	        			output = '<h3>'+oInfo.natoobl+' область</h3>';
	        			output += '<ul>';
		        			output += '<li>';
		        				output += '<div class="label">Коатуу</div>';
		        				output += '<div class="data">'+oInfo.koatuu[0]+'</div>';
		        			output += '</li>';
	        			output += '</ul>';	        				
	        		}	 
        			

        			if (popup){
    					popup.destroy();
    					popup=false;
    			    }
    		    	
    		    	popup = new OpenLayers.Popup.FramedCloud(		                   
                            "chicken", 
                            map.getLonLatFromPixel(event.xy),
                            null,
                            output,
                            null,
                            true	                     
      		        );				    
    			    popup.closeOnMove = true;
    			    popup.autoSize = true;				 
    			    map.addPopup(popup);        		
				    
                }
            }
        });
        
        map.addControl(infoo);
        infoo.activate();


      }// End of INIT
            
            // sets the HTML provided into the nodelist element
           /* function setHTML(response){
                document.getElementById('nodelist').innerHTML = response.responseText;
            };*/
            
            // shows/hide the control panel
            function toggleControlPanel(event){
                var toolbar = document.getElementById("toolbar");
                if (toolbar.style.display == "none") {
                    toolbar.style.display = "block";
                }
                else {
                    toolbar.style.display = "none";
                }
                event.stopPropagation();
                map.updateSize()
            }
            
            
            // Transition effect, can be null or 'resize'
            function setTransitionMode(transitionEffect){
                if (transitionEffect === 'resize') {
                    tiled.transitionEffect = transitionEffect;
                    untiled.transitionEffect = transitionEffect;
                }
                else {
                    tiled.transitionEffect = null;
                    untiled.transitionEffect = null;
                }
            }
                
            function setPalette(mode){
                if (mode == '') {
                    tiled.mergeNewParams({
                        palette: null
                    });
                    untiled.mergeNewParams({
                        palette: null
                    });
                }
                else {
                    tiled.mergeNewParams({
                        palette: mode
                    });
                    untiled.mergeNewParams({
                        palette: mode
                    });
                }
            }
            
            function setWidth(size){
                var mapDiv = document.getElementById('map');
                var wrapper = document.getElementById('wrapper');
                
                if (size == "auto") {
                    // reset back to the default value
                    mapDiv.style.width = null;
                    wrapper.style.width = null;
                }
                else {
                    mapDiv.style.width = size + "px";
                    wrapper.style.width = size + "px";
                }
                // notify OL that we changed the size of the map div
                map.updateSize();
            }
            
            function setHeight(size){
                var mapDiv = document.getElementById('map');
                
                if (size == "auto") {
                    // reset back to the default value
                    mapDiv.style.height = null;
                }
                else {
                    mapDiv.style.height = size + "px";
                }
                // notify OL that we changed the size of the map div
                map.updateSize();
            }
                                    
            function mergeNewParams(params){
                tiled.mergeNewParams(params);
                untiled.mergeNewParams(params);
            }

	        function osm_getTileURL(bounds) {
	            var res = this.map.getResolution();
	            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	            var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	            var z = this.map.getZoom();
	            var limit = Math.pow(2, z);

	            if (y < 0 || y >= limit) {
	                return "http://www.maptiler.org/img/none.png";
	            } else {
	                x = ((x % limit) + limit) % limit;
	                return this.url + z + "/" + x + "/" + y + "." + this.type;
	            }
	        }

	        function overlay_getTileURL(bounds) {
	            var res = this.map.getResolution();
	            var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	            var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
	            var z = this.map.getZoom();
	            if (this.map.baseLayer.name == 'Virtual Earth Roads' || this.map.baseLayer.name == 'Virtual Earth Aerial' || this.map.baseLayer.name == 'Virtual Earth Hybrid') {
	               z = z + 1;
	            }
		        if (mapBounds.intersectsBounds( bounds ) && z >= mapMinZoom && z <= mapMaxZoom ) {
	               //console.log( this.url + z + "/" + x + "/" + y + "." + this.type);
		        //alert (map.layers[4].visibility);
				if (map.layers[4].visibility == true) {	
		               		return "http://212.26.144.107:8092/ukraine_jpg/" + z + "/" + x + "/" + y + "." + this.type
				};
				if (map.layers[5].visibility = true) {
                                return "http://212.26.144.107:8092/333/" + z + "/" + x + "/" + y + "." + this.type
                };
           
			
                } else {
			//alert;
                   return "http://www.maptiler.org/img/none.png";
                }
	        }	

		   function getWindowHeight() {
		        if (self.innerHeight) return self.innerHeight;
		        if (document.documentElement && document.documentElement.clientHeight)
		            return document.documentElement.clientHeight;
		        if (document.body) return document.body.clientHeight;
			        return 0;
		    }

		    function getWindowWidth() {
			    if (self.innerWidth) return self.innerWidth;
			    if (document.documentElement && document.documentElement.clientWidth)
			        return document.documentElement.clientWidth;
			    if (document.body) return document.body.clientWidth;
			        return 0;
		    }

		    function resize() {  
			    var map = document.getElementById("map");
			    var leftSideWidth = 0; 
			    
			    map.style.height = (getWindowHeight()-72) + "px";
			    
			    if($('.sidebar').is(':visible')) leftSideWidth = 280;			    
			    	
			    map.style.width = (getWindowWidth()-2-leftSideWidth) + "px";
				if (map.updateSize) { map.updateSize(); };
		    } 
		    
		    function getParcelInfo(koatuu, zone, quartal, parcel)
		    {
		    	var ret;
		    	$.ajax({
					url : '/kadastrova-karta/get-parcel-Info',
					dataType: 'json',
					async: false,
					data : {'koatuu' : koatuu, 'zone' : zone, 'quartal' : quartal, 'parcel' : parcel},
					success :function(data){   
						ret =  data;
					}});
		    	return ret['data'];
		    }		    
		    
		    onresize=function(){ resize(); };
		    
		    
		    
		    